//
//  TestTextLabel.swift
//  FZSFImageBrowser
//
//  Created by huangqiong on 2021/8/12.
//  Copyright © 2021 李雷川. All rights reserved.
//

import UIKit

class TestTextLabel: UIView {

    var attributeStr:NSMutableAttributedString?
    var contentSize:CGSize = .zero
    
    
  override init(frame:CGRect) {
    super.init(frame: frame)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        let context = UIGraphicsGetCurrentContext()
        context?.textMatrix = .identity
        //CFAttributedString
        let attrString = self.attributeStr! as CFAttributedString
        let framesetter = CTFramesetterCreateWithAttributedString(attrString)
        //作用范围

        let rangeAll = CFRangeMake(0,self.attributeStr?.length ?? 0)
        var fitRange:CFRange = .init()
        //获取适应的尺寸。竖直展示这里设置height为无穷大，width为0，意思就是，高度可以无限长，宽度由AttributedString的文字决定， 如果想要设置为横着展示，则width设置为无穷大， height设置为0
        let s = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, rangeAll,nil,CGSize.init(width:0, height:CGFloat(MAXFLOAT)), &fitRange)
        //coretext的原点坐标(0,0)在左下角，UIKit的原点坐标(0,0)系在左上角,这里要把UIKit的坐标转为
        context?.translateBy(x:0, y: self.frame.height)
        //翻转矩阵， 把画面翻转过来， 如果不设置这个，那么出现的效果就好像是照镜子一样，可以自行尝试
        context?.scaleBy(x:1, y:-1)
        //设置坐标 L 形坐标系, 因为原本是横着展示的，现在要竖直展示，所以需要交换s的宽高， s.width实际上现在变成了文字的高度
        let frameRect = CGRect.init(x: (self.frame.width-s.height)/2.0, y: (self.frame.height-s.width)/2.0, width: s.height, height: s.width)
        
        //笔画路径
        let framePath:CGPath=CGPath.init(rect: frameRect, transform:nil)
        //.leftToRight 竖直状态，从左边往右读，.rightToLeft从右往左读，.topToBottom 横着的状态
        /*如果是竖直的状态， 需要attributeString 也设置为竖直的形式


                 var attriStr = NSMutableAttributedString.init(string: text, attributes: [.foregroundColor: UIColor.red,.font:UIFont.exoBoldFont(size: 14), .verticalGlyphForm: true])

                  也就是这句代码：.verticalGlyphForm: true

                */
        let progressionNumber = NSNumber.init(value:CTFrameProgression.rightToLeft.rawValue)

        // CTFrameProgression 一定要先转成number类型，否则会crash
        let dic = [kCTFrameProgressionAttributeName:progressionNumber as CFNumber]
        let frame = CTFramesetterCreateFrame(framesetter, rangeAll, framePath, dic as CFDictionary)
        CTFrameDraw(frame , context!)
    }
}
